<html>
<head>
    <meta charset="utf-8">
    <title>Кристалловед</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <link href="css/bootstrap.css" rel="stylesheet">
    <link href="css/bootstrap-responsive.css" rel="stylesheet">
    <style type="text/css">
        .nlm {
            margin-left:0 !important;
        }
        body {
            margin: 50px 10px;
            padding: 0;
        }
        @media (max-width: 979px) {
          body {
            margin: 0;
            padding-top: 0;
          }
        }
    </style>
    <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <!--link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" /-->
    <script src="js/jquery.js"></script>
    <script src="js/jquery-ui.min.js"></script>
    <script type="text/javascript" src="js/bootstrap.min.js"></script>
    <script type="text/javascript">


//Порт к которому подключен Arduino
var settings = {
    serialPort: 'COM16',
    weaponTypes:{
         "t_0":"Мечь",
         "t_1":"Топор",
         "t_2":"Пика",
         "t_3":"Алебарда",
         "t_4":"Булава"
    },
    crystallTypes:{
         "t_0":"Универсальный",
         "t_1":"Оружие",
         "t_2":"Доспех"
    },
    types:{
        "t_-1":{
            name: "Не отформаниторан",
            description: "Устройство является новым и не отформатированным ни под один тип",
        },
        "t_0":{
            name: "Отключено",
            description: "Устройство не активно и имеет неизвестный тип",
        },
        "t_1":{
            name: "Кристалл памяти игрока",
            description: "настройки игрока",
            tab: "player_settings",
            img: 'Knight-icon-big.png'
        },
        "t_2":{
            name: "Кристалл памяти оружия",
            description: "настройки оружия",
            tab: "weapon_settings",
            img: 'sword-icon-big.png'
        },
        "t_3":{
            name: "Кристалл памяти доспеха",
            description: "настройки доспеха",
            tab: "armor_settings",
            img: 'shield-icon-big.png'
        },
        "t_4":{
            name: "Простой кристалл улучшения",
            description: "просто память",
            tab: "crystall_settings",
            img: 'ruby-icon-big.png'
        }
    },
    gameSettings:{
        id: 3656,
        params:[
            {
                name: "Live", 
                description: "Player live level",
                critical: true,
                min: 0,
                img: 'live.png'
            },
            {
                name: "Manna", 
                description: "Player magic power level",
                critical: false,
                min: 0,
                img: 'mana.png'
            },
            {
                name: "P.Defence", 
                description: "Phusical defence",
                critical: false,
                min: 0,
                img: 'shield-icon.png'
            },
            {
                name: "M.Defence", 
                description: "Magic defence",
                critical: false,
                min: 0,
                img: 'm_shield-icon.png'
            }
        ]
    }
}
//непосредственно управляющая функция
var Arduino = function(mode, start, read, data,callback){
    var mode = mode;
    var read = read;
    var callback = callback;
    var command = mode+(start*1 || 0)+"("+(read*1 || 1)+")["+(data? (typeof data == "object" ? data.join('_') : data+"|") : "")+"]";
    $.get('c.py',{
        c:command,
        p:settings.serialPort
    }, function(data){
        data = $.trim(data);
        console.log(data);
        if(typeof callback == 'function'){
            if(mode == "r" || mode == "w"){
                data = read>1 || mode == "w" ? data.split("|") : [data];
                for(var i in data){
                    data[i] = data[i]*1
                }
            }
            callback(data);
        }
    });
}

//Отображение контролов
var Controller = function(){
    this.updated = true;
    this.ports = 13;
    this.currentTab = 'settings';
    this.container = $('#list');
    this.player_settings = new player_settings_class();
    this.weapon_settings = new weapon_settings_class();
    this.armor_settings = new armor_settings_class();
    this.crystall_settings = new crystall_settings_class();
    this.init_crystall = new init_crystall_class();
    this.settings = new settings_class();
    this.pushList = [];
    this.start = function(){
        var self = this;
        $(".arduinoAction").on('click', function(){
            self[$(this).data("function")]();
        });
    }
    this.initData = function(){
        var that = this;
        $('#initResult').html('Загрузка...');
        Arduino("r",0,2,false,function(data){
            console.log(data);
            var type = settings.types['t_'+data[1]];
            if(undefined == type) {
                type = settings.types['t_-1'];
                var name = type.name+" "+data[1];
            }else{
                var name = type.name;
            }
            $('#initResult').html('<br/><div class="span12" id="crystallInfoBlock"><div><b>ID</b>: '+data[0]+'</div>\
                <div><b>Тип</b>: '+name+'</div>\
                <div><b>Описание</b>: '+type.description+'</div></div><br/>');
            if(data[1] <1) return;
            $('#initResult').append($('<button>')
                .attr('class', "btn arduinoAction")
                .text('Использовать')
                .click(function(){ 
                    that.useChip(data)
                })
            );
            switch(data[1]){
                case 1:{
                    Arduino("p",50,50,false,function(data){
                        data = data.split('|')[0];
                        $('#crystallInfoBlock').append('<hr /><img src="img/'+type.img+'" style="float:left; margin-right:20px"/><h3>'+data+'</h3>');
                        Arduino("r",4,2,false,function(data){
                            $('#crystallInfoBlock').append('<div><b>ID</b>: '+data[0]+'</div>\
                                <div><b>ID группы</b>: '+data[1]+'</div>');
                            
                        });
                    });
                    
                }break;
                case 2:{
                    Arduino("p",20,50,false,function(data){
                        data = data.split('|')[0];
                        $('#crystallInfoBlock').append('<hr /><img src="img/'+type.img+'" style="float:left; margin-right:20px"/><h3>'+data+'</h3>');
                        Arduino("r",6,1,false,function(data){
                            $('#crystallInfoBlock').append('<div><b>Тип</b>: '+settings.weaponTypes['t_'+data[0]]+'</div>');
                        });
                    });
                    
                }break;
                case 4:{
                    Arduino("p",20,50,false,function(data){
                        data = data.split('|')[0];
                        $('#crystallInfoBlock').append('<hr /><img src="img/'+type.img+'" style="float:left; margin-right:20px"/><h3>'+data+'</h3>');
                        Arduino("r",6,1,false,function(data){
                            $('#crystallInfoBlock').append('<div><b>Тип</b>: '+settings.crystallTypes['t_'+data[0]]+'</div>');
                        });
                    });
                    
                }break;
            }
        });
    }
    this.useChip = function(data){
        console.log('UseChip function', data);
        this.updated = false;
        $('#baseMenu a[href="#'+settings.types['t_'+data[1]].tab+'"]').tab('show');
        this.load();
    }
    this.load = function(){
        controller[controller.currentTab].load();
    }
    this.save = function(){
        controller[controller.currentTab].save();
    }
    this.clean = function(){
        
    }
    this.reset = function(){
        
    }
    this.pushData = function(data, callback){
        controller.pushList = data;
        var saveElement = function(element,callback){
            Arduino(element[0],element[1],element[2],element[3],function(data){
                if(controller.pushList.length){
                    setTimeout(function(){
                        saveElement(controller.pushList.shift(),callback);
                    }, 100);
                }else if(typeof callback == 'function') callback();
            });
        }
        saveElement(controller.pushList.shift(),callback);
    }
    this.showAlert = function(text){
        $('#alertText').html(text);
        $('#topAlert').show();
        setTimeout(function(){
            $('#topAlert').hide();
        },3000);
    }
    this.buildElementSelect = function(i, data, useproc){
        useproc = useproc || false;
        var elementSelect = $("<select>").attr('class','span12')
            .attr('data-num',i)
            .attr('data-param','element')
            .change(function(){
                data.params[$(this).data('num')].element = $(this).val().split('_')[0]*1;
                data.params[$(this).data('num')].param = 10*($(this).val().split('_')[1]*1+1) + $(this).val().split('_')[2]*1;
            })
        for(var m = 0; m<settings.gameSettings.params.length; m++){
            elementSelect.append('<optgroup label="'+settings.gameSettings.params[m].name+'">');
            elementSelect.append('<option value="'+m+'_0_0">'+settings.gameSettings.params[m].name+' (базовое)</option>');
            if(useproc)elementSelect.append('<option value="'+m+'_0_1">'+settings.gameSettings.params[m].name+' (базовое) %</option>');
            elementSelect.append('<option value="'+m+'_1_0">'+settings.gameSettings.params[m].name+' (максимальное)</option>');
            if(useproc)elementSelect.append('<option value="'+m+'_1_1">'+settings.gameSettings.params[m].name+' (максимальное) %</option>');
            elementSelect.append('<option value="'+m+'_2_0">'+settings.gameSettings.params[m].name+' (прирост)</option>');
            if(useproc)elementSelect.append('<option value="'+m+'_2_1">'+settings.gameSettings.params[m].name+' (прирост) %</option>');
            elementSelect.append('<option value="'+m+'_3_0">'+settings.gameSettings.params[m].name+' (базовое ВРЕМЕННО)</option>');
            if(useproc)elementSelect.append('<option value="'+m+'_3_1">'+settings.gameSettings.params[m].name+' (базовое ВРЕМЕННО) %</option>');
            elementSelect.append('<option value="'+m+'_4_0">'+settings.gameSettings.params[m].name+' (максимальное ВРЕМЕННО)</option>');
            if(useproc)elementSelect.append('<option value="'+m+'_4_1">'+settings.gameSettings.params[m].name+' (максимальное ВРЕМЕННО) %</option>');
            elementSelect.append('<option value="'+m+'_5_0">'+settings.gameSettings.params[m].name+' (прирост ВРЕМЕННО)</option>');
            if(useproc)elementSelect.append('<option value="'+m+'_5_1">'+settings.gameSettings.params[m].name+' (прирост ВРЕМЕННО) %</option>');
            elementSelect.append('</optgroup><optgroup></optgroup>');
        }
        return elementSelect;
    }
    this.start();
}

//////////////////////////////////////////////////////////////////////////////

var init_crystall_class = function(){
    this.show = function(){

    }
    this.save = function(){
        
    }
    this.load = function(){
        
    }
    this.clean = function(){
        
    }
}

var settings_class = function(){
    this.show = function(){
        $('#comport_name').val(settings.serialPort);
        $('#gameSettings').append("<legend>ID игры</legend><br/>");
        $('#gameSettings').append($("<div></div>").attr('class','span11').append(
            $("<input>").attr("type","text")
                .attr('class','span2')
                .val(settings.gameSettings.id)
                .change(function(){
                    settings.gameSettings.id = this.value
                })
            )
        );
        $('#gameSettings').append("<legend>Параметры игры</legend><div class='span11'><div style='float:left'>#</div><div class='span2'>Название (10 букв)</div><div class='span5'>Описание (70 букв)</div><div class='span2'>Минимальное</div><div class='span2'>Жизненно важно</div></div>");
        for(var i = 0; i<settings.gameSettings.params.length; i++){
            var div = $("<div class='span11'></div>");
            div.append($("<div>"+i+"</div>").css('float','left'));
            div.append($("<div><img src='img/"+settings.gameSettings.params[i].img+"' style='margin-right:10px'/></div>").css("whiteSpace","nowrap")
                .attr('class','span2').append(
                    $("<input>").attr("type","text")
                        .attr('class','span8')
                        .attr('data-num',i)
                        .val(settings.gameSettings.params[i].name)
                        .change(function(){
                            this.value = this.value.substr(0,10);
                            settings.gameSettings.params[$(this).data('num')].name = this.value;
                        })
                    )
                );
            div.append($("<div></div>").attr('class','span5').append(
                $("<input>").attr("type","text")
                    .attr('class','span12')
                    .attr('data-num',i)
                    .val(settings.gameSettings.params[i].description)
                    .change(function(){
                        this.value = this.value.substr(0,70);
                        settings.gameSettings.params[$(this).data('num')].description = this.value;
                    })
                )
            );
            div.append($("<div></div>").attr('class','span2').append(
                $("<input>").attr("type","text")
                    .attr('class','span12')
                    .attr('data-num',i)
                    .val(settings.gameSettings.params[i].min)
                    .change(function(){
                        this.value = parseInt(this.value) || 0;
                        settings.gameSettings.params[$(this).data('num')].min = this.value;
                    })
                )
            );
            div.append($("<div></div>").attr('class','span2').append(
                $("<input>").attr("type","checkbox")
                    .attr('class','span12')
                    .attr('data-num',i)
                    .attr('checked',settings.gameSettings.params[i].critical)
                    .change(function(){
                        settings.gameSettings.params[$(this).data('num')].critical = this.checked;
                    })
                )
            );
            $('#gameSettings').append(div);
        }
    }
    this.save = function(){
        
    }
    this.load = function(){
        
    }
    this.clean = function(){
        
    }
}

var player_settings_class = function(){
    this.data = {
        selfId: 0,
        userId: 0,
        groupId: 0,
        name: "",
        params:[]
    };
    this.changeParam = function(el){
        var num = el.data('num');
        if(undefined == this.data.params[num]) this.data.params[num] = {
            current: 0,
            max: 0,
            inc: 0
        };
        this.data.params[num][el.data('param')] = el.val()*1;
    }
    this.show = function(){
        var that = this;
         $('#player_settings form [name=self_id]').val(this.data.selfId);
        $('#player_settings form [name=user_id]').val(this.data.userId);
        $('#player_settings form [name=group_id]').val(this.data.groupId);
        $('#player_settings form [name=user_name]').val(this.data.name);
        $("#user_params_value").html("<span class='span2 hide'></span>");
        for(var i = 0; i<settings.gameSettings.params.length; i++){
            var div = $("<div class='span11'></div>").append("<span class='span3' style='white-space:nowrap'><img src='img/"+settings.gameSettings.params[i].img+"' style='margin-right:10px'/><b>"+settings.gameSettings.params[i].name+"</b></span>");
            $(['current','max','inc']).each(function(){
                div.append($("<div></div>").attr('class','span2').append(
                    $("<input>").attr("type","text")
                        .attr('class','span12')
                        .attr('data-num',i)
                        .attr('data-param',this)
                        .val(that.data.params[i] ? that.data.params[i][this] : "")
                        .change(function(){
                            that.changeParam($(this));
                        })
                    )
                );
            });
            $("#user_params_value").append(div);
        }
    }
    this.save = function(){
        var that = this;
        var data = [
            ["w",0,0,[this.data.selfId,1,this.data.userId,this.data.groupId]],
            ["s",50,50,that.data.name],
            ["w",10000,2,[settings.gameSettings.id, settings.gameSettings.params.length]]
        ];
        for(var i = 0; i<settings.gameSettings.params.length; i++){
            if(undefined == this.data.params[i]) this.data.params[i] = {
                current: 0,
                max: 0,
                inc: 0
            };
            data.push(["w",100+10*i,    0,  [this.data.params[i].current, this.data.params[i].max, this.data.params[i].inc]]);
            data.push(["s",10100+100*i, 10, settings.gameSettings.params[i].name]);
            //data.push(["s",10110+100*i,   70, settings.gameSettings.params[i].description]);
            data.push(["w",10180+100*i, 2,  [settings.gameSettings.params[i].critical ? 1 : 0 , settings.gameSettings.params[i].min]]);
        }
        controller.pushData(data, function(){
                console.log('Saved');
                controller.showAlert('Данные сохранены');
        });
    }
    this.load = function(){
        var that = this;
        Arduino("r",0,4,false,function(data){
            that.data.selfId = data[0]*1;
            that.data.userId = data[2]*1;
            that.data.groupId = data[3]*1;
            Arduino("p",50,50,false,function(data){
                that.data.name = data.split('|')[0];
                Arduino("r",100,settings.gameSettings.params.length*10,false,function(data){
                    for(var i = 0; i<settings.gameSettings.params.length; i++){
                        that.data.params[i] = {
                            current: data[i*5],
                            max: data[i*5+1],
                            inc: data[i*5+2]
                        };
                    }
                    that.show();
                });
            });
        });
        
    }
    this.clean = function(){
        
    }
}

var weapon_settings_class = function(){
    this.data = {
        selfId: 0,
        gameId: 0,
        type: 0,
        name: "",
        delay: 300,
        level: 300,
        owner: 0,
        params:[
            {
                id: 23,
                type: 0,
                param: 0,
                element: 0,
                value: 100,
                defender: 2,
                time: 0
            }
        ]
    };
    this.changeParam = function(el){
        var num = el.data('num');
        this.data.params[num][el.data('param')] = el.val()*1;
    }
    this.show = function(){
        var that = this;
        $('#weapon_settings form [name=self_id]').val(this.data.selfId);
        $('#weapon_settings form [name=game_id]').val(this.data.gameId);
        $('#weapon_settings form [name=type]').val(this.data.type);
        $('#weapon_settings form [name=weapon_name]').val(this.data.name);
        $('#weapon_settings form [name=delay]').val(this.data.delay);
        $('#weapon_settings form [name=level]').val(this.data.level);
        $('#weapon_settings form [name=owner]').val(this.data.owner);
        $("#weapon_value").html("");
        for(var i in settings.weaponTypes) {
            $('#weapon_settings form [name=type]').append($("<option value='"+(i.split('_')[1])+"'>").text(settings.weaponTypes[i]));
        }
        for(var i = 0; i<this.data.params.length; i++){
            this.createLine(i);
        }
    }
    this.createLine = function(i){
        var data = this.data.params[i]
        var that = this;
        var div = $("<div></div>")
            .attr('class','span12')
            .css('marginLeft', 0);
        div.append($("<div></div>").attr('class','span2').append(
            $("<input>").attr("type","text")
                .attr('class','span12')
                .attr('data-num',i)
                .attr('data-param','id')
                .val(data.id)
                .change(function(){
                    that.changeParam($(this));
                })
            )
        );
        var typeSelect = $("<select>").attr('class','span12')
            .attr('data-num',i)
            .attr('data-param','type')
            .change(function(){
                that.data.params[$(this).data('num')].type = $(this).val()*1;
            })
            typeSelect.append('<option value="0">На врага</option>');
            typeSelect.append('<option value="1">На себя постоянно</option>');
            typeSelect.append('<option value="2">На себя при ударе</option>');
            typeSelect.append('<option value="3">На себя при убийстве</option>');
        div.append($("<div></div>").attr('class','span2').append(typeSelect.val(data.type)));
        var sel = controller.buildElementSelect(i, that.data, true);
        div.append($("<div></div>").attr('class','span2').append(sel));
        var p = [parseInt(data.param/10)-1,data.param - parseInt(data.param/10)*10];
        sel.val(data.element+"_"+p[0]+"_"+p[1]);
        div.append($("<div></div>").attr('class','span2').append(
            $("<input>").attr("type","text")
                .attr('class','span12')
                .attr('data-num',i)
                .attr('data-param','value')
                .val(data.value)
                .change(function(){
                    that.changeParam($(this));
                })
            )
        );
        var defenderSelect = $("<select>").attr('class','span12')
            .attr('data-num',i)
            .attr('data-param','defender')
            .change(function(){
                that.changeParam($(this));
            });
        defenderSelect.append('<option value="0">--</option>');
        for(var m = 1; m<settings.gameSettings.params.length; m++){
            defenderSelect.append('<option value="'+m+'">'+settings.gameSettings.params[m].name+'</option>');
        }
        div.append($("<div></div>").attr('class','span2').append(defenderSelect.val(data.defender)));
        div.append($("<div></div>").attr('class','span1').append(
            $("<input>").attr("type","text")
                .attr('class','span12')
                .attr('data-num',i)
                .attr('data-param','time')
                .val(data.time)
                .change(function(){
                    that.changeParam($(this));
                })
            )
        );
        div.append($("<div></div>").attr('class','span1').append(
            $("<input>").attr("type","button")
                .attr('class','btn btn-warning')
                .attr('data-num',i)
                .val('-')
                .click(function(){
                    that.data.params[$(this).data('num')] = false;
                    $(this).parent().parent().remove();
                })
            )
        );
        $("#weapon_value").append(div);
    }
    this.save = function(){
        var tmp = [];
        for(var i = 0; i<this.data.params.length; i++){
            if(this.data.params[i] !== false) tmp.push(this.data.params[i]);
        }
        var that = this;
        var data = [
            ["w",0,0,[
                this.data.selfId, 
                2, 
                this.data.gameId || settings.gameSettings.id,
                this.data.type,
                tmp.length,
                this.data.level,
                this.data.delay,
                this.data.owner
            ]],
            ["s",20,50,that.data.name]
        ];
        for(var i = 0; i<tmp.length; i++){
            data.push(["w",100+50*i, 0, [
                tmp[i].id,
                tmp[i].type,
                tmp[i].element,
                tmp[i].param,
                tmp[i].value,
                tmp[i].defender,
                tmp[i].time
            ]]);
        }
        console.log(data);
        controller.pushData(data, function(){
                console.log('Saved');
                controller.showAlert('Данные сохранены');
        });
    }
    this.load = function(){
        var that = this;
          $("#weapon_value>div").remove();
        Arduino("r",0,8,false,function(data){
            that.data.selfId = data[0]*1;
            that.data.gameId = data[2]*1;
            that.data.type = data[3]*1;
            var paramlength = data[4]*1;
            that.data.level = data[5]*1; 
            that.data.delay = data[6]*1; 
            that.data.owner = data[7]*1;
            Arduino("p",20,50,false,function(data){
                that.data.name = data.split('|')[0];
                Arduino("r",100,25*paramlength,false,function(data){
                    that.data.params = [];
                    for(var i = 0; i<paramlength; i++){
                        that.data.params[i] ={
                            id: data[i*25],
                            type: data[i*25+1],
                            element: data[i*25+2],
                            param: data[i*25+3],
                            value: data[i*25+4],
                            defender: data[i*25+5],
                            time: data[i*25+6]
                        };
                        that.createLine(i);
                    }
                    that.show();
                });
            });
        });
    }
    this.clean = function(){
        
    }
    var that = this;
        $('#addWeaponLine').click(function(){
            var i = that.data.params.length;
            that.data.params.push({
                id: 0,
                type: 0,
                param: 0,
                element: 0,
                value: 0,
                defender: 0,
                time: 0
            });
            that.createLine(i);
        });
}

var armor_settings_class = function(){
    this.show = function(){

    }
    this.save = function(){
        
    }
    this.load = function(){
        
    }
    this.clean = function(){
        
    }
}

var crystall_settings_class = function(){
    this.data = {
        selfId: 0,
        gameId: 0,
        type: 0,
        name: "",
        params:[
            {
                id: 24,
                groupId: 0,
                param: 0,
                element: 0,
                value: 100,
                defender: 0,
                manna: 0,
                count: 0,
                maxCount: 0
            }
        ]
    };
    this.changeParam = function(el){
        var num = el.data('num');
        this.data.params[num][el.data('param')] = el.val()*1;
    }
    this.show = function(){
        var that = this;
        $('#crystall_settings form [name=self_id]').val(this.data.selfId);
        $('#crystall_settings form [name=game_id]').val(this.data.gameId);
        $('#crystall_settings form [name=crystall_name]').val(this.data.name);
        $("#crystall_value").html("");
        $('#crystall_settings form [name=type]').html("");
        for(var i in settings.crystallTypes) {
            $('#crystall_settings form [name=type]').append($("<option value='"+(i.split('_')[1])+"'>").text(settings.crystallTypes[i]));
        }
        $('#crystall_settings form [name=type]').val(this.data.type);
        for(var i = 0; i<this.data.params.length; i++){
            this.createLine(i);
        }
    }
    this.createLine = function(i){
        var data = this.data.params[i]
        var that = this;
        var div = $("<div></div>")
            .attr('class','span12')
            .css('marginLeft', 0);
        div.append($("<div></div>").attr('class','span1').append(
            $("<input>").attr("type","text")
                .attr('class','span12')
                .attr('data-num',i)
                .attr('data-param','id')
                .val(data.id)
                .change(function(){
                    that.changeParam($(this));
                })
            )
        );
        div.append($("<div></div>").attr('class','span1').append(
            $("<input>").attr("type","text")
                .attr('class','span12')
                .attr('data-num',i)
                .attr('data-param','groupId')
                .val(data.groupId)
                .change(function(){
                    that.changeParam($(this));
                })
            )
        );
        var sel = controller.buildElementSelect(i, that.data, true);
        div.append($("<div></div>").attr('class','span2').append(sel));
        var p = [parseInt(data.param/10)-1,data.param - parseInt(data.param/10)*10];
        sel.val(data.element+"_"+p[0]+"_"+p[1]);
        div.append($("<div></div>").attr('class','span1').append(
            $("<input>").attr("type","text")
                .attr('class','span12')
                .attr('data-num',i)
                .attr('data-param','value')
                .val(data.value)
                .change(function(){
                    that.changeParam($(this));
                })
            )
        );
        var defenderSelect = $("<select>").attr('class','span12')
            .attr('data-num',i)
            .attr('data-param','defender')
            .change(function(){
                that.changeParam($(this));
            });
        defenderSelect.append('<option value="0">--</option>');
        for(var m = 1; m<settings.gameSettings.params.length; m++){
            defenderSelect.append('<option value="'+m+'">'+settings.gameSettings.params[m].name+'</option>');
        }
        div.append($("<div></div>").attr('class','span2').append(defenderSelect.val(data.defender)));
        div.append($("<div></div>").attr('class','span1').append(
            $("<input>").attr("type","text")
                .attr('class','span12')
                .attr('data-num',i)
                .attr('data-param','manna')
                .val(data.manna)
                .change(function(){
                    that.changeParam($(this));
                })
            )
        );
        div.append($("<div></div>").attr('class','span1').append(
            $("<input>").attr("type","text")
                .attr('class','span12')
                .attr('data-num',i)
                .attr('data-param','count')
                .val(data.count)
                .change(function(){
                    that.changeParam($(this));
                })
            )
        );
        div.append($("<div></div>").attr('class','span1').append(
            $("<input>").attr("type","text")
                .attr('class','span12')
                .attr('data-num',i)
                .attr('data-param','maxCount')
                .val(data.maxCount)
                .change(function(){
                    that.changeParam($(this));
                })
            )
        );
        div.append($("<div></div>").attr('class','span1').append(
            $("<input>").attr("type","button")
                .attr('class','btn btn-warning')
                .attr('data-num',i)
                .val('-')
                .click(function(){
                    that.data.params[$(this).data('num')] = false;
                    $(this).parent().parent().remove();
                })
            )
        );
        $("#crystall_value").append(div);
    }
    this.save = function(){
        var tmp = [];
        for(var i = 0; i<this.data.params.length; i++){
            if(this.data.params[i] !== false) tmp.push(this.data.params[i]);
        }
        var that = this;
        var data = [
            ["w",0,0,[
                this.data.selfId, 
                4, 
                this.data.gameId || settings.gameSettings.id,
                this.data.type,
                tmp.length
            ]],
            ["s",20,50,that.data.name]
        ];
        for(var i = 0; i<tmp.length; i++){
            data.push(["w",100+50*i, 0, [
                tmp[i].id,
                tmp[i].groupId,
                tmp[i].element,
                tmp[i].param,
                tmp[i].value,
                tmp[i].defender,
                tmp[i].manna,
                tmp[i].count,
                tmp[i].maxCount
            ]]);
        }
        console.log(data);
        controller.pushData(data, function(){
                console.log('Saved');
                controller.showAlert('Данные сохранены');
        });
    }
    this.load = function(){
        var that = this;
          $("#crystall_value>div").remove();
        Arduino("r",0,5,false,function(data){
            that.data.selfId = data[0]*1;
            that.data.gameId = data[2]*1;
            that.data.type = data[3]*1;
            var paramlength = data[4]*1;
            Arduino("p",20,50,false,function(data){
                that.data.name = data.split('|')[0];
                Arduino("r",100,25*paramlength,false,function(data){
                    that.data.params = [];
                    for(var i = 0; i<paramlength; i++){
                        that.data.params[i] ={
                            id: data[i*25],
                            groupId: data[i*25+1],
                            element: data[i*25+2],
                            param: data[i*25+3],
                            value: data[i*25+4],
                            defender: data[i*25+5],
                            manna: data[i*25+6],
                            count: data[i*25+7],
                            maxCount: data[i*25+8]
                        };
                        that.createLine(i);
                    }
                    that.show();
                });
            });
        });
    }
    this.clean = function(){
        
    }
    var that = this;
        $('#addCrystallLine').click(function(){
            var i = that.data.params.length;
            that.data.params.push({
                id: 0,
                groupId: 0,
                param: 0,
                element: 0,
                value: 0,
                defender: 0,
                manna: 0,
                count: 0,
                maxCount: 0,
            });
            that.createLine(i);
        });
}
$(document).ready(function(){
    controller = new Controller();
    $('a[data-toggle="tab"]').on('show', function (e) {
        var tab = e.target.href.split('#')[1];
        controller.currentTab = tab;
        controller[tab].show();
    });
    controller.settings.show();
});
    </script>
</head>
<body>
    <div class="alert alert-success" id='topAlert' style='position: absolute; margin: 0; left: 0; right: 0; top: 40px; display:none'>
        <button type="button" class="close" data-dismiss="alert">&times;</button>
        <span id='alertText'></span>
    </div> 
    <div class="navbar navbar-inverse navbar-fixed-top"><div class='navbar-inner'>
        <ul class="nav">
            <li class='span3'><a class="brand" href="#"><img src="img/ruby-gear-icon.png" style="margin-right:10px"/>Кристалловед</a></li>
            <li><a href="#" class="arduinoAction" data-function="load"><img src="img/ruby-put-icon.png" style="margin-right:10px"/>Зазгрузить</a></li>
            <li><a href="#" class="arduinoAction" data-function="save"><img src="img/ruby-get-icon.png" style="margin-right:10px"/>Сохранить</a></li>
            <li><a href="#" class="arduinoAction" data-function="clean"><img src="img/ruby-icon.png" style="margin-right:10px"/>Очистить</a></li>
            <li><a href="#" class="arduinoAction" data-function="reset"><img src="img/ruby-delete-icon.png" style="margin-right:10px"/>Стереть память</a></li>
        </ul>
    </div></div>
    <div class="container-fluid">
        <div class="row-fluid">
            <div class="span3">
                <ul class="nav nav-pills nav-stacked"  id="baseMenu">
                    <li><a href="#init_crystall" data-toggle="tab"><img src="img/recherche-icon.png" style="margin-right:10px"/>Инициализация</a></li>
                    <li><a href="#player_settings" data-toggle="tab"><img src="img/Knight-icon.png" style="margin-right:10px"/>Память игрока</a></li>
                    <li><a href="#weapon_settings" data-toggle="tab"><img src="img/sword-icon.png" style="margin-right:10px"/>Память оружия</a></li>
                    <li><a href="#armor_settings" data-toggle="tab"><img src="img/shield-icon.png" style="margin-right:10px"/>Память брони</a></li>
                    <li><a href="#crystall_settings" data-toggle="tab"><img src="img/ruby-icon.png" style="margin-right:10px"/>Кристалл улучшений</a></li>
                    <li class="active"><a href="#settings" data-toggle="tab"><img src="img/Settings-icon.png" style="margin-right:10px"/>Настройки</a></li>
                </ul>
            </div>
            <div class="span9">
                <div class="tab-content">
                    <div class="tab-pane" id="init_crystall">
                        <img src="img/recherche-icon-big.png" style='float:left; margin-right:20px'/>
                        <h1>Инициализация кристалла</h1>
                        <div class='span5'><button class="btn span8 arduinoAction" data-function="initData">Инициализация</button></div>
                        <div class='span11' id="initResult"></div>
                    </div>
                    <div class="tab-pane" id="player_settings">
                        <img src="img/Knight-icon-big.png" style='float:left; margin-right:20px'/>
                        <h1>Память игрока</h1>
                        <form class='span11'>
                            <fieldset>
                                <legend>Идентефикация</legend>
                                <div class="span11"><br/>
                                    <span class='span2'>ID</span>
                                    <span class='span2'>ID пользователя</span>
                                    <span class='span2'>ID группы</span>
                                    <span class='span5'>Имя</span>
                                </div>
                                <div class="span11"><span class='span2 hide'></span>
                                    <span class='span2'><input class='span12' type="text" name="self_id" onChange="controller.player_settings.data['selfId'] = this.value*1" /></span>
                                    <span class='span2'><input class='span12' type="text" name="user_id" onChange="controller.player_settings.data['userId'] = this.value*1" /></span>
                                    <span class='span2'><input class='span12' type="text" name="group_id" onChange="controller.player_settings.data['groupId'] = this.value*1" /></span>
                                    <span class='span5'><input class='span12' type="text" name="user_name" onChange="controller.player_settings.data['name'] = this.value.substr(0,50)" /></span>
                                </div>
                            </fieldset>
                            <fieldset>
                                <legend>Параметры</legend>
                                <div class="span11"><br/>
                                    <span class='span3'>Название</span>
                                    <span class='span2'>Значение</span>
                                    <span class='span2'>Максимум</span>
                                    <span class='span2'>Прирост</span>
                                </div>
                                <div class="span11" id='user_params_value'></div>
                            </fieldset>
                        </form>
                    </div>
                    <div class="tab-pane" id="weapon_settings">
                        <img src="img/sword-icon-big.png" style='float:left; margin-right:20px'/>
                        <h1>Настройка оружия</h1>
                        <form class='span11'>
                            <fieldset>
                                <legend>Идентефикация</legend>
                                <div class="span11"><br/>
                                    <span class='span2'>ID</span>
                                    <span class='span2'>ID игры</span>
                                    <span class='span2'>Тип</span>
                                    <span class='span5'>Имя</span>
                                </div>
                                <div class="span11"><span class='span2 hide'></span>
                                    <span class='span2'><input class='span12' type="text" name="self_id" onChange="controller.weapon_settings.data['selfId'] = this.value*1" /></span>
                                    <span class='span2'><input class='span12' type="text" name="game_id" onChange="controller.weapon_settings.data['gameId'] = this.value*1" /></span>
                                    <span class='span2'><select class='span12' type="text" name="type" onChange="controller.weapon_settings.data['type'] = this.value*1">
                                    </select></span>
                                    <span class='span5'><input class='span12' type="text" name="weapon_name" onChange="controller.weapon_settings.data['name'] = this.value.substr(0,50)" /></span>
                                </div>
                                <br/>
                                <div class="span11"><br/>
                                    <span class='span4'>Срабатывание (порог акселерометра)</span>
                                    <span class='span4'>Задержка (между ударами в мс)</span>
                                    <span class='span2'>ID владельца</span>
                                </div>
                                <div class="span11"><span class='span2 hide'></span>
                                    <span class='span4'><input class='span12' type="text" name="level" onChange="controller.weapon_settings.data['level'] = this.value*1" /></span>
                                    <span class='span4'><input class='span12' type="text" name="delay" onChange="controller.weapon_settings.data['delay'] = this.value*1" /></span>
                                    <span class='span2'><input class='span12' type="text" name="owner" onChange="controller.weapon_settings.data['owner'] = this.value*1" /></span>
                                </div>
                            </fieldset>
                            <fieldset>
                                <legend>Воздействия</legend>
                                <div class="span12" style='margin-left:0'>
                                    <span class='span2' style='margin-left:0'>ID</span>
                                    <span class='span2'>Тип</span>
                                    <span class='span2'>Элемент</span>
                                    <span class='span2'>Значение</span>
                                    <span class='span2'>Защита</span>
                                    <span class='span1'>Время</span>
                                </div>
                                <div class="span12" id='weapon_value' style='margin-left:0'></div>
                                <input type='button' class='btn btn-success' id="addWeaponLine" value="+ Добавить"\>
                            </fieldset>
                        </form>
                    </div>
                    <div class="tab-pane" id="armor_settings">
                        <img src="img/shield-icon-big.png" style='float:left; margin-right:20px'/>
                        <h1>Настройка брони</h1>
                    </div>
                    <div class="tab-pane" id="crystall_settings">
                        <img src="img/ruby-icon-big.png" style='float:left; margin-right:20px'/>
                        <h1>Кристалл улучшений</h1>
                        <form class='span11'>
                            <fieldset>
                                <legend>Идентефикация</legend>
                                <div class="span11"><br/>
                                    <span class='span2'>ID</span>
                                    <span class='span2'>ID игры</span>
                                    <span class='span2'>Тип</span>
                                    <span class='span5'>Имя</span>
                                </div>
                                <div class="span11"><span class='span2 hide'></span>
                                    <span class='span2'><input class='span12' type="text" name="self_id" onChange="controller.crystall_settings.data['selfId'] = this.value*1" /></span>
                                    <span class='span2'><input class='span12' type="text" name="game_id" onChange="controller.crystall_settings.data['gameId'] = this.value*1" /></span>
                                    <span class='span2'><select class='span12' type="text" name="type" onChange="controller.crystall_settings.data['type'] = this.value*1"></select></span>
                                    <span class='span5'><input class='span12' type="text" name="crystall_name" onChange="controller.crystall_settings.data['name'] = this.value.substr(0,50)" /></span>
                                </div>
                            </fieldset>
                            <fieldset>
                                <legend>Воздействия</legend>
                                <div class="span12" style='margin-left:0'>
                                    <span class='span1' style='margin-left:0'>ID</span>
                                    <span class='span1'>Группы</span>
                                    <span class='span2'>Элемент</span>
                                    <span class='span1'>Значение</span>
                                    <span class='span2'>Защита</span>
                                    <span class='span1'>Манна</span>
                                    <span class='span1'>Зарядов</span>
                                    <span class='span1'>Всего зарядов</span>
                                </div>
                                <div class="span12" id='crystall_value' style='margin-left:0'></div>
                                <input type='button' class='btn btn-success' id="addCrystallLine" value="+ Добавить"\>
                            </fieldset>
                        </form>
                    </div>
                    <div class="tab-pane active" id="settings">
                        <h1>Настройки</h1>
                        <form>
                            <fieldset>
                                <legend>Настройки порта</legend>
                                <div class="span11"><br/>
                                    <input class='span2' type="text" id="comport_name" placeholder="имя порта например COM5" onChange="settings.serialPort = this.value">
                                </div>
                            </fieldset>
                        <br/>
                        <br/>
                        <h1>Настройки игры</h1>
                            <fieldset id='gameSettings'>
                            </fieldset>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>